package com.fast.fast.common.mybatis.plus.interceptor;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.fast.fast.common.mybatis.plus.config.MyBatisPlusProperties;
import com.fast.fast.common.mybatis.plus.context.CustomContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.schema.Column;

import java.util.*;

/**
 * MybatisPlus自定义多租户拦截器
 *
 * @author lyf
 * @date 2022/01/01 00:00 周六
 * @date 2024/09/12 17:10 周四
 **/
@RequiredArgsConstructor
@Slf4j
public class CustomTenantInterceptor implements TenantLineHandler {

    private final CustomContext context;

    private final MyBatisPlusProperties myBatisPlusProperties;

    @Override
    public Expression getTenantId() {
        Long tenantId = context.getCurrentTenantId();
        log.debug("当前租户id是：{}", tenantId);
        return tenantId == null ? null : new LongValue(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        return "tenant_id";
    }

    @Override
    public boolean ignoreTable(String tableName) {
        // 放行的表名
        Set<String> excludeTables = new HashSet<>();
        excludeTables.add("sys_tenant");

        Optional.ofNullable(myBatisPlusProperties.getTenantInterceptor().getExcludeTables())
                .orElse(Collections.emptySet())
                .stream()
                .filter(ObjUtil::isNotEmpty)
                .map(String::trim)
                .forEach(excludeTables::add);
        return excludeTables.stream().anyMatch(e -> e.equalsIgnoreCase(tableName));
    }

    @Override
    public boolean ignoreInsert(List<Column> columns, String tenantIdColumn) {
        return TenantLineHandler.super.ignoreInsert(columns, tenantIdColumn);
    }
}
